<template>
    <div>
      <!--    面包屑导航区-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!--    卡片视图区-->
      <el-card>
<!--        警告区域-->
        <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
<!--        选择商品分类区域-->
       <el-row>
         <el-col class="goodsOpt">
           <span>选择商品分类:</span>
         </el-col>
         <el-col>
<!--           options用来指定数据源, props：用来指定配置对象-->
           <el-cascader
             v-model="selectKeys"
             :options="goodsCateList"
             :props="paramsProps"
             @change="handleChange">
           </el-cascader>
         </el-col>
       </el-row>
<!--        tab页签区域-->
        <el-tabs v-model="activeName" @tab-click="tabClick">
<!--          添加动态参数的面板-->
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" :disabled="isBtnDisabled" @click="showDialog">添加参数</el-button>
            <!--        参数列表区域-->
            <el-table
              :data="manyDataTable"
              style="width: 100%">
<!--              下拉列表区域-->
              <el-table-column
                width="100"
                type="expand">
                <template slot-scope="scope">
<!--                  标签区-->
                  <el-tag
                    v-for="(item,i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="handleClose(i, scope.row)"
                  >
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="参数" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="editParamsDialog(scope.row.attr_id)">修改</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!--          添加静态属性的面板-->
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" :disabled="isBtnDisabled" @click="showDialog">添加属性</el-button>
            <!--        属性列表区域-->
            <el-table
              :data="onlyDataTable"
              style="width: 100%">
              <el-table-column
                width="100"
                type="expand">
                <template slot-scope="scope">
                  <!--                  标签区-->
                  <el-tag
                    v-for="(item,i) in scope.row.attr_vals"
                    :key="i"
                    closable
                   >
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column label="#" type="index"></el-table-column>
              <el-table-column label="参数" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="editParamsDialog(scope.row.attr_id)">修改</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
<!--      添加参数和属性的对话框-->
      <el-dialog
        :title="'添加'+ titleText"
        :visible.sync="addParamsDialogVisible"
        width="50%"
        @close="addParamsDialogClosed"
        >
<!--        添加参数的对话框中的表单-->
        <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="addParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
      </el-dialog>
      <!--      修改参数和属性的对话框-->
      <el-dialog
        :title="'修改'+ titleText"
        :visible.sync="editParamsDialogVisible"
        width="50%"
        @close="editParamsDialogClosed"
      >
        <!--        修改参数的对话框中的表单-->
        <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="editParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'params',
  data () {
    return {
      // 配置对象
      paramsProps: {
        expandTrigger: 'hover',
        // 是否严格的遵守父子节点不互相关联  默认为false
        // checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品分类列表的数据
      goodsCateList: [],
      // 级联选择框双向绑定到的数组
      selectKeys: [],
      // tab页签区域中被激活的页签名称
      activeName: 'many',
      // 参数列表的数据
      manyDataTable: [],
      // 属性列表的数据
      onlyDataTable: [],
      // 控制添加参数对话框的显示与隐藏
      addParamsDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      editParamsDialogVisible: false,
      // 添加参数的表单  添加表单验证的对象
      addParamsForm: {
        attr_name: ''
      },
      editParamsForm: {
        attr_name: '',
        attr_id: ''
      },
      // 定义验证规则
      addParamsRules: {
        attr_name: [{
          required: true, message: '请输入合法的参数名称', trigger: 'blur'
        }]
      },
      editParamsRules: {
        attr_name: [{
          required: true, message: '请输入合法的参数名称', trigger: 'blur'
        }]
      },
      // 控制输入框显示与隐藏
      inputVisible: false,
      // 与输入框双向绑定的数据
      inputValue: ''
    }
  },
  created () {
    this.getGoodsCateList()
  },
  methods: {
    // 获取商品分类的列表数据
    async getGoodsCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.goodsCateList = res.data
      console.log(this.goodsCateList)
    },
    // 选择项发生改变所触发的函数
    handleChange () {
      this.getParamsData()
    },
    // tab点击时触发
    tabClick () {
      this.getParamsData()
    },
    // 获取参数的列表数据,若写在handleChange函数中则只对级联选择器选项栏发生改变的时候起作用,而当tab页改变时拿不到数据
    // 所以要重新定义一个函数,使得参数列表能够被多个函数使用
    async getParamsData () {
      // console.log(this.selectKeys)
      // 只能为第三级分类设置参数,所以当不是第三级时,不能选中
      if (this.selectKeys.length !== 3) {
        // 把分类的数组清空重置
        this.selectKeys = []
        // 清空参数列表的数据
        this.manyDataTable = []
        // 清空属性列表的数据
        this.onlyDataTable = []
        return
      }
      // 如果等于3就是第三级
      // 根据所选分类的id和当前所处的面板,发送请求,获取对应的参数列表数据;把获取到的id值作为参数发送请求
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      // 把res.data进行循环遍历中拿出attr_value的每一项形成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 因为每一个item共用一个v-model所以会产生给一个参数添加新tag,其余的也会添加,所以我们要为每一个item设置自己的属性
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      if (this.activeName === 'many') {
        this.manyDataTable = res.data
      } else {
        this.onlyDataTable = res.data
      }
      this.$message.success('获取数据')
    },
    // 展示对话框
    showDialog () {
      this.addParamsDialogVisible = true
    },
    // 点击修改按钮,弹出的对话框
    async editParamsDialog (id) {
      this.editParamsForm.attr_id = id
      console.log(id)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
        params: {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      console.log(res.data)
      this.editParamsForm = res.data
      // this.$message.success('编辑参数成功')
      this.editParamsDialogVisible = true
    },
    // 监听对话框的关闭事件
    addParamsDialogClosed () {
      this.$refs.addParamsRef.resetFields()
    },
    editParamsDialogClosed () {
      this.$refs.editParamsRef.resetFields()
    },
    // 点击确定对参数与验证并且提交数据
    addParams () {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.getParamsData()
        this.addParamsDialogVisible = false
        this.$message.success('添加参数成功')
      })
    },
    editParams () {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑参数失败')
        }
        this.getParamsData()
        this.editParamsDialogVisible = false
        this.$message.success('编辑参数成功')
      })
    },
    // 点击删除弹出提示框,点击确认删除之后发送请求
    async removeParams (id) {
      console.log(id)
      const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('您取消删除参数的操作')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/` + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // 点击+ New Tag按钮打开输入框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick方法的作用:就是当页面元素被重新渲染之后,才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入框失去焦点时,隐藏输入框,优化:当我们输入的字符串不合法:比如说一堆空格这时候就需要判断一下
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果没有return的话就说明用户输入了真实的数据,这时就要把文本框输入的值添加到标签数组中,并且上传到后台数据中去
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 把添加的标签上传到后台数据中去
      this.saveAttrValues(row)
    },
    async saveAttrValues(row) {
      // 把添加的标签上传到后台数据中去
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数成功')
    },
    // 删除对应的参数可选项
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrValues(row)
    }
  },
  computed: {
    // 如果按钮需要被禁用,返回true,否则返回false
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的id,通过id值去请求数据
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    // 对话框提示信息
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.goodsOpt{
  margin: 15px 0;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
  .el-tag{
    margin-right: 5px;
  }
</style>
